<template>
  <div class="account-layout">
    <div class="account-search">
      <Collapse>
        <Panel name="1">
          <Button type="primary" icon="ios-search">搜索</Button>
          <div slot="content" class="account-search-inp">
            <Input v-model="searchData" placeholder="请输入..." class="fl"></Input>
            <Button type="primary" icon="ios-search" class="fl"></Button>
          </div>
        </Panel>
      </Collapse>
    </div>
    <div class="account-table">
      <div class="account-table-title">
        <h2>系统设置<span>账号管理</span></h2>
        <div class="account-table-add">
          <Button type="primary" icon="edit" @click="addAccountList">新增账号</Button>
        </div>
      </div>
      <div class="account-table-main">
        <Table border :columns="tableData" :data="accountTableData"></Table>
        <div class="account-table-page clearfix">
          <Page :total="totalNum" show-elevator show-total class="fr" @on-change="getAccountData"></Page>
        </div>
      </div>
    </div>
    <!--账号信息编辑-->
    <Modal v-model="accountModal"
           :title="accountTitle"
           @on-ok="accountListSubmit('account')"
           class="edit-modal"
           :mask-closable="false"
           :loading="loading">
      <Form ref="account" :rules="accountRules" :model="account" :label-width="106">
        <FormItem prop="loginName" label="账号：">
          <Input v-model="account.loginName" placeholder="请输入账号名" :disabled="editName"></Input>
        </FormItem>
        <FormItem prop="password" label="密码：">
          <Input v-model="account.password" placeholder="请输入密码" type="password"></Input>
        </FormItem>
        <FormItem prop="mobilePhone" label="座机号：" v-if="phoneNum">
          <Input v-model="account.mobilePhone" placeholder="请输入座机号"></Input>
        </FormItem>
        <FormItem prop="telePhone" label="手机号：" v-if="phoneNum">
          <Input v-model="account.telePhone" placeholder="请输入手机号"></Input>
        </FormItem>
        <FormItem prop="roleId" label="角色：">
          <Select v-model="account.roleId" placeholder="请选择角色">
            <Option :value="item.id.toString()" v-for="(item,index) in roleData" :key="index">{{item.name}}
            </Option>
          </Select>
        </FormItem>
        <FormItem prop="isUsed" label="状态：">
          <RadioGroup v-model="account.isUsed">
            <Radio label="1">启用</Radio>
            <Radio label="0">禁用</Radio>
          </RadioGroup>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
  export default {
    data () {
      return {
        loginName: JSON.parse(sessionStorage.getItem('loginName')),
        loginId: JSON.parse(sessionStorage.getItem('loginId')),
        companyId: JSON.parse(sessionStorage.getItem('companyId')),
        searchData: '',
        tableData: [
          {
            title: '账号',
            key: 'loginName'
          },
          {
            title: '密码',
            key: 'password'
          },
          {
            title: '角色',
            key: 'name',
            render: (h, params) => {
              return h('div', [
                h('Icon', {
                  props: {
                    type: 'person'
                  }
                }),
                h('strong', params.row.name)
              ])
            }
          },
          {
            title: '状态',
            key: 'isUsed'
          },
          {
            title: '创建时间',
            key: 'createTime',
            sortable: true
          },
          {
            title: '操作',
            key: 'action',
            width: 160,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    icon: 'edit'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(params.index)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small',
                    icon: 'trash-b'
                  },
                  on: {
                    click: () => {
                      this.remove(params.index)
                    }
                  }
                }, '删除')
              ])
            }
          }
        ],
        totalNum: 0,
        accountData: [],
        accountTableData: [],
        roleData: [],
        // 弹窗
        accountModal: false,
        accountTitle: '',
        loading: true,
        account: {},
        editName: false,
        phoneNum: true,
        accountRules: {
          loginName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 2, max: 30, message: '长度在2-30之间', toggle: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 2, max: 30, message: '长度在2-30之间', toggle: 'blur'}
          ],
          mobilePhone: [
            {required: true, message: '请输入座机号', trigger: 'blur'}
          ],
          telePhone: [
            {required: true, message: '请输入手机号', trigger: 'blur'}
          ],
          roleId: [
            {required: true, message: '请选择角色', trigger: 'change'}
          ],
          isUsed: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ]
        }
      }
    },
    created () {
      // 第一步：获取角色信息
      this.getRoleData()
      // 第二步：获取账户信息
      this.getAccountData(1)
    },
    methods: {
      // 获取角色信息
      getRoleData () {
        let url = this.api.role.getRole
        let params = {
          companyId: this.companyId
        }
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.roleData = res.data.data
          } else {
            this.$Message.error({content: '请配置相关信息', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      // 获取账户信息
      getAccountData (pageNum) {
        let params = {
          pageNum: pageNum
        }
        let url = this.api.account.getAccount
        this.$axios.get(url, {params: params || {}}).then((res) => {
          this.accountData = []
          this.accountTableData = []
          if (res.data.msg.code === '20000') {
            let page = res.data.page
            this.totalNum = page.total
            let data = res.data.data
            for (let i = 0; i < data.length; i++) {
              let obj = {
                loginName: data[i].loginName,
                password: data[i].password,
                name: data[i].name,
                isUsed: data[i].isUsed === 1 ? '启用' : '禁用',
                createTime: data[i].createTime,
                roleId: data[i].roleId,
                id: data[i].id,
                userId: data[i].userId
              }
              let obj2 = {
                loginName: data[i].loginName,
                password: '******',
                name: data[i].name,
                isUsed: data[i].isUsed === 1 ? '启用' : '禁用',
                createTime: data[i].createTime,
                roleId: data[i].roleId,
                id: data[i].id,
                userId: data[i].userId
              }
              this.accountData.push(obj)
              this.accountTableData.push(obj2)
            }
          } else {
            this.$Message.error({content: '请配置相关信息', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      // 修改账户信息
      upAccountData (params) {
        let url = this.api.account.updateAccount
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.getAccountData(1)
          } else {
            this.$Message.error({content: '请配置相关信息', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      // 新增账户信息
      addAccountData (params) {
        let url = this.api.account.addAccount
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            this.getAccountData(1)
          } else {
            this.$Message.error({content: '请配置相关信息', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      // 删除账户信息
      deleteAccountData (params) {
        let url = this.api.account.deleteAccount
        this.$axios.get(url, {params: params}).then((res) => {
          if (res.data.msg.code === '20000') {
            console.log(res.data)
          } else {
            this.$Message.error({content: '请配置相关信息', duration: 5})
          }
        }).catch((err) => {
          if (err) throw err
          this.$Message.error({content: '网络异常', duration: 5})
        })
      },
      // 获取修改账户信息数据
      edit (index) {
        this.accountModal = true
        console.log(this.accountData[index])
        this.account = {
          type: 'updateAccount',
          id: this.accountData[index].id,
          userId: this.accountData[index].userId,
          loginName: this.accountData[index].loginName, // 用户名
          password: this.accountData[index].password,  // 密码
          roleId: this.accountData[index].roleId.toString(),  // 密码
          isUsed: this.accountData[index].isUsed === '启用' ? '1' : '0' // 是否启用
        }
        this.editName = true
        this.phoneNum = false
        this.accountTitle = '账户编辑'
      },
      // 获取删除账户信息数据
      remove (index) {
        let obj = {
          id: this.accountData[index].id,
          userId: this.accountData[index].userId
        }
        this.deleteAccountData(obj)
        this.getAccountData(1)
      },
      // 获取新增账户信息数据
      addAccountList () {
        this.accountModal = true
        this.editName = false
        this.phoneNum = true
        this.accountTitle = '新增账户'
        this.account = {
          type: 'addAccount',
          loginName: '', // 用户名
          password: '',  // 密码
          mobilePhone: '', // 座机号
          telePhone: '', // 手机号
          roleId: '', // 角色
          isUsed: '' // 是否启用
        }
      },
      // 确认修改账户信息
      accountListSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$Message.success('提交中。。。')
            if (this.account.type === 'updateAccount') {
              let params = {
                modifier: this.loginId,
                companyId: this.companyId,
                id: this.account.id,
                password: this.account.password,
                isUsed: this.account.isUsed - 0,
                roleId: this.account.roleId - 0,
                userId: this.account.userId - 0
              }
              console.log(params)
              this.upAccountData(params)
            } else if (this.account.type === 'addAccount') {
              let roleId = this.account.roleId
              for (let i = 0; i < this.roleData.length; i++) {
                if (roleId === this.roleData[i].id.toString()) {
                  this.account.name = this.roleData[i].name
                }
              }
              let params = {
                companyId: this.companyId, // 登录时获取
                creater: this.loginId, // 登录的id
                loginName: this.account.loginName, // 用户名
                password: this.account.password,  // 密码
                mobilePhone: this.account.mobilePhone, // 座机号
                telePhone: this.account.telePhone, // 手机号
                isUsed: this.account.isUsed - 0, // 是否启用
                roleId: this.account.roleId - 0, // 角色Id,
                name: this.account.name // 角色类型
              }
              this.addAccountData(params)
            }
            setTimeout(() => {
              this.accountModal = false
            }, 500)
          } else {
            this.$Message.error('表单验证失败!')
            this.loading = false
            setTimeout(() => {
              this.loading = true
            }, 1)
          }
        })
      }
    }
  }
</script>
